package org.jeecg.modules.engineering.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.engineering.entity.EquipCollectInfo;
import org.jeecg.modules.engineering.entity.EquipCollectItem;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.engineering.entity.EquipDataCollectorCode;
import org.jeecg.modules.engineering.entity.EquipDataCollector;
import org.jeecg.modules.engineering.vo.EquipDataCollectorPage;
import org.jeecg.modules.engineering.service.IEquipDataCollectorService;
import org.jeecg.modules.engineering.service.IEquipDataCollectorCodeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 设备数据采集商表
 * @Author: jeecg-boot
 * @Date:   2019-08-27
 * @Version: V1.0
 */
@RestController
@RequestMapping("/b/engineering/equipDataCollector")
@Slf4j
public class EquipDataCollectorController {
	@Autowired
	private IEquipDataCollectorService equipDataCollectorService;
	@Autowired
	private IEquipDataCollectorCodeService equipDataCollectorCodeService;
	
	/**
	  * 分页列表查询
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<EquipDataCollector>> queryPageList(String collectorName,String collectorCode,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Result<IPage<EquipDataCollector>> result = new Result<IPage<EquipDataCollector>>();
		Page<EquipDataCollector> page = new Page<EquipDataCollector>(pageNo, pageSize);
		IPage<EquipDataCollector> pageList = equipDataCollectorService.selectSqlList(page,collectorName,collectorCode);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 列表查询
	  * @param equipDataCollector
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "设备数据采集商-列表查询所有采集商")
	 @ApiOperation(value="设备数据采集商-列表查询所有采集商", notes="设备数据采集商-列表查询所有采集商")
	 @GetMapping(value = "/listAll")
	 public Result<List<EquipDataCollector>> queryListAll(EquipDataCollector equipDataCollector,
														HttpServletRequest req) {
		 Result<List<EquipDataCollector>> result = new Result<>();
		 QueryWrapper<EquipDataCollector> queryWrapper = QueryGenerator.initQueryWrapper(equipDataCollector, req.getParameterMap());
		 List<EquipDataCollector> list = equipDataCollectorService.list(queryWrapper);
		 result.setSuccess(true);
		 result.setResult(list);
		 return result;
	 }

	/**
	  *   添加
	 * @param equipDataCollectorPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<EquipDataCollector> add(@RequestBody EquipDataCollectorPage equipDataCollectorPage) {
		Result<EquipDataCollector> result = new Result<EquipDataCollector>();
		try {
			EquipDataCollector equipDataCollector = new EquipDataCollector();
			BeanUtils.copyProperties(equipDataCollectorPage, equipDataCollector);
			
			equipDataCollectorService.saveMain(equipDataCollector, equipDataCollectorPage.getEquipDataCollectorCodeList());
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param equipDataCollectorPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<EquipDataCollector> edit(@RequestBody EquipDataCollectorPage equipDataCollectorPage) {
		Result<EquipDataCollector> result = new Result<EquipDataCollector>();
		EquipDataCollector equipDataCollector = new EquipDataCollector();
		BeanUtils.copyProperties(equipDataCollectorPage, equipDataCollector);
		EquipDataCollector equipDataCollectorEntity = equipDataCollectorService.getById(equipDataCollector.getId());
		if(equipDataCollectorEntity==null) {
			result.error500("未找到对应实体");
		}else {
			//boolean ok = equipDataCollectorService.updateById(equipDataCollector);
			equipDataCollectorService.updateMain(equipDataCollector, equipDataCollectorPage.getEquipDataCollectorCodeList());
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			equipDataCollectorService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<EquipDataCollector> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<EquipDataCollector> result = new Result<EquipDataCollector>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.equipDataCollectorService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<EquipDataCollector> queryById(@RequestParam(name="id",required=true) String id) {
		Result<EquipDataCollector> result = new Result<EquipDataCollector>();
		EquipDataCollector equipDataCollector = equipDataCollectorService.getById(id);
		if(equipDataCollector==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(equipDataCollector);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryEquipDataCollectorCodeByMainId")
	public Result<List<EquipDataCollectorCode>> queryEquipDataCollectorCodeListByMainId(@RequestParam(name="id",required=true) String id) {
		Result<List<EquipDataCollectorCode>> result = new Result<List<EquipDataCollectorCode>>();
		List<EquipDataCollectorCode> equipDataCollectorCodeList = equipDataCollectorCodeService.selectByMainId(id);
		result.setResult(equipDataCollectorCodeList);
		result.setSuccess(true);
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<EquipDataCollector> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              EquipDataCollector equipDataCollector = JSON.parseObject(deString, EquipDataCollector.class);
              queryWrapper = QueryGenerator.initQueryWrapper(equipDataCollector, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<EquipDataCollectorPage> pageList = new ArrayList<EquipDataCollectorPage>();
      List<EquipDataCollector> equipDataCollectorList = equipDataCollectorService.list(queryWrapper);
      for (EquipDataCollector equipDataCollector : equipDataCollectorList) {
          EquipDataCollectorPage vo = new EquipDataCollectorPage();
          BeanUtils.copyProperties(equipDataCollector, vo);
          List<EquipDataCollectorCode> equipDataCollectorCodeList = equipDataCollectorCodeService.selectByMainId(equipDataCollector.getId());
          vo.setEquipDataCollectorCodeList(equipDataCollectorCodeList);
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "设备数据采集商表列表");
      mv.addObject(NormalExcelConstants.CLASS, EquipDataCollectorPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("设备数据采集商表列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<EquipDataCollectorPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EquipDataCollectorPage.class, params);
              for (EquipDataCollectorPage page : list) {
                  EquipDataCollector po = new EquipDataCollector();
                  BeanUtils.copyProperties(page, po);
                  equipDataCollectorService.saveMain(po, page.getEquipDataCollectorCodeList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
